package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.nurseapp.dao.MealListMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.dto.OrdersReviewDTO;
import com.haoze.nurseapp.enumeration.VarCodeEnum;
import com.haoze.nurseapp.service.OperationService;
import com.haoze.nurseapp.vo.OrderRevieInfoDetailByInpatVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @Author: lufq
 * @CreateTime: 2020-12-05
 */
@Service
public class OperationServiceImpl  implements OperationService {
    @Autowired
    private MealListMapper mealListMapper;
    //@Value("${his.url.operationUrl2}")
    //private String operationUrl2;

    public Result query(int page, int pageSize, String wardId,String dateTime,String keyWords){
        String allInpatNum = mealListMapper.queryPatientMedicalNumByWardDeptId(wardId, null, keyWords);
        PageHelper.startPage(page,pageSize);
        List<Map<String, Object>> list = mealListMapper.getOperationArrangement(wardId, allInpatNum, dateTime, keyWords);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genOkResult(pageInfo);

        //String dataTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        /*List<Map<String,String>> list = new CopyOnWriteArrayList<>();
        List<Map<String,String>> operationList = new CopyOnWriteArrayList<>();
        int totalLength = 0;
        //查询病区代码
        //调用his
        Map<String, String> params = new HashMap<String, String>();
        String allInpatNum = mealListMapper.queryPatientMedicalNumByWardDeptId(wardId, null, keyWords);
        if(StringUtils.isNotBlank(allInpatNum)){
            params.put("inpatNum",allInpatNum);
            params.put("in_date",dateTime);
            params.put("flag", "2");
            params.put("operationID", ConstantEnum.HIS_OPERATION_10012.getKey());

            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl2, params);
            if (null != jsonObject) {
                if (jsonObject.getString("data") != null) {
                    list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {});
                    List<String> inpatNumList = new CopyOnWriteArrayList();
                    if(!CollectionUtils.isEmpty(list)){
                        for(Map<String,String> map:list){
                            inpatNumList.add(map.get("PATIENT_ID")+"-1");
                            String operationName = map.get("OPERATION_NAME");
                            int serialNumber = 1;
                            if(StringUtils.isNotBlank(operationName)){
                                String[] operationNames = operationName.split(",");
                                for(String operName:operationNames) {
                                    Map<String, String> reMap = new CopyOnWriteMap<>();
                                    reMap.putAll(map);
                                    reMap.put("OPERATION_NAME",operName);
                                    reMap.put("serialNumber",serialNumber+"");
                                    serialNumber++;
                                    operationList.add(reMap);
                                }
                            }

                        }
                        //
                        List<Map<String, String>> operationWardList = mealListMapper.queryOperationInfoByInpatNum(inpatNumList);
                        List<Map<String, String>> oList = new CopyOnWriteArrayList<>();
                        if(!CollectionUtils.isEmpty(operationWardList)){
                            Map<String, List<Map<String, String>>> collect = operationWardList.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
                            if(collect!=null) {
                                for (String key : collect.keySet()) {
                                    String[] keys = key.split("#");
                                    Map<String, String> reMap = new HashMap<>();
                                    reMap.put("BED_NO",keys[2]);
                                    reMap.put("INPAT_NUM",keys[1]);
                                    for (Map<String, String> map:collect.get(key)) {
                                        if(StringUtils.isNotBlank(map.get("varCode")) && VarCodeEnum.ORDER_SS_SSMC.getVarCode().equals(map.get("varCode"))){
                                            //手术名称
                                            reMap.put("OPERATION_NAME",map.get("dataValue"));
                                        }else if(StringUtils.isNotBlank(map.get("varCode")) && VarCodeEnum.ORDER_SSRQ.getVarCode().equals(map.get("varCode"))){
                                            //手术时间
                                            reMap.put("APPOINTMENT_TIME",map.get("dataValue"));
                                        }else if(StringUtils.isNotBlank(map.get("varCode")) && VarCodeEnum.ZHENDUAN.getVarCode().equals(map.get("varCode"))){
                                            //诊断
                                            reMap.put("DIAGNOSIS",map.get("dataValue"));
                                        }
                                    }
                                    oList.add(reMap);
                                }
                            }
                        }
                        for(Map<String,String> map:operationList){
                            String inpatNum = map.get("PATIENT_ID")+"-1";
                            String operationName = map.get("OPERATION_NAME");
                            boolean flag=false;
                            for(Map<String, String> operation:oList){
                                if(inpatNum.equals(operation.get("INPAT_NUM"))){
                                    map.put("BED_NO",operation.get("BED_NO"));
                                    //手术名称
                                    if(StringUtils.isNotBlank(operationName) &&  operationName.equals(operation.get("OPERATION_NAME"))){
                                        map.put("APPOINTMENT_TIME",operation.get("APPOINTMENT_TIME"));
                                        map.put("DIAGNOSIS",operation.get("DIAGNOSIS"));
                                        flag=true;
                                        break;
                                    }
                                }
                            }
                            String scheduledDateTime = map.get("SCHEDULED_DATE_TIME");
                            if(StringUtils.isNotBlank(scheduledDateTime) && scheduledDateTime.length()>=16){
                                map.put("SCHEDULED_DATE_TIME",scheduledDateTime.substring(0,16));
                            }
                            if(!flag){
                                map.put("APPOINTMENT_TIME",map.get("SCHEDULED_DATE_TIME"));
                                map.put("DIAGNOSIS",null);
                                map.put("BED_NO",mealListMapper.queryBedNoByInpatNum(map.get("PATIENT_ID")+"-1"));
                            }
                        }

                    }
                }
            }

            if(!CollectionUtils.isEmpty(operationList)){
                operationList = operationList.stream().sorted(Comparator.comparing(OperationServiceImpl::comparingByAppointmentTime)
                        .thenComparingInt(OperationServiceImpl::comparingByBedNo))
                        .collect(Collectors.toList());
                totalLength = operationList.size();

                if (page != 0 && pageSize != 0) {
                    operationList = operationList.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                }
            }
        }

        PageInfo<Map<String,String>> pageInfo = new PageInfo<>(operationList);
        pageInfo.setTotal(totalLength);
        return ResultGenerator.genOkResult(pageInfo);*/


    }

    private static String fetchGroupKey(Map<String,String> operation){
        return operation.get("emrFileId")+"#"+operation.get("inpatNum")+"#"+operation.get("bedNo");
    }

    private static String comparingByAppointmentTime(Map<String, String> map){
        return map.get("APPOINTMENT_TIME");
    }
    private static Integer comparingByBedNo(Map<String, String> map){
        return Integer.parseInt(map.get("BED_NO"));
    }
    private static Integer comparingBySerialNumber(Map<String, String> map){
        return Integer.parseInt(map.get("serialNumber"));
    }
}
